<?php
/*
 * @Date: 2021-05-08 10:52:54
 * @Author: yukun
 * @LastEditors: yukun
 * @LastEditTime: 2021-05-08 11:38:33
 * @FilePath: /design-patterns-study/观察者模式/UserSubject.php
 * @Description: 本文件主要功能为：
 */

class UserSubject implements SplSubject
{
    protected $observers = null;

    /** @var int 登陆次数 */
    public $loginNum = 0;
    /** @var string 兴趣爱好 */
    public $hobby    = '';
    
    public function __construct()
    {
        $this->observers = new SplObjectStorage();
    }

    public function setLoginNum($loginNum)
    {
        $this->loginNum = $loginNum;
    }

    public function setHobby($hobby)
    {
        $this->hobby    = $hobby;
    }

    public function login()
    {
        // TODO 登陆相关的操作。。。

        $this->notify();

    }

    public function attach(SplObserver $observer)
    {
        $this->observers->attach($observer);
    }

    public function detach(SplObserver $observer)
    {
        $this->observers->detach($observer);
    }

    public function notify()
    {
        $this->observers->rewind();
        while ($this->observers->valid()) {
            $observer = $this->observers->current();
            $observer->update($this);
            $this->observers->next();
        }
    }
}
